package top.soulblack.purchasesale.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: 廉雪峰
 * @Date: 2019/5/8 17:28
 * @Version 1.0FF
 */
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.soulblack.purchasesale.common.Result;
import top.soulblack.purchasesale.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static top.soulblack.purchasesale.common.CodeMsg.*;

@Controller
public class IndexController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public Result<Boolean> login(String username, String password) {
        // 密码MD5加密
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return Result.success(true);
        } catch (UnknownAccountException e) {
            return Result.error(SORT_ERROR);
        } catch (IncorrectCredentialsException e) {
            return Result.error(COLOR_EDIT_ERROR);
        } catch (LockedAccountException e) {
            return Result.error(SIZE_LIFE);
        } catch (AuthenticationException e) {
            return Result.error(BRAND_EDIT_ERROR);
        }
    }

    @GetMapping("/403")
    public String forbid() {
        return "403";
    }

    @RequestMapping("/")
    public String redirectIndex() {
        return "redirect:/index";
    }

    @RequestMapping("/index")
    public String index(Model model) {
        // 登录成后，即可通过Subject获取登录的用户信息
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("user", user);
        return "index";
    }
}
